package cn.codeforfun.initialization.project;

import cn.codeforfun.initialization.common.Pagination;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Optional;

/**
 * @author wangbin
 */
@Service
public class ProjectService {
    @Resource
    private ProjectRepository projectRepository;

    Pagination<Project> listProject(Pagination<Project> pagination) {
        PageRequest pageRequest = PageRequest.of(pagination.getPageNo() - 1, pagination.getPageSize());
        Page<Project> all = projectRepository.findAll(pageRequest);
        pagination.setData(all.getContent());
        pagination.setCount(all.getTotalElements());
        return pagination;
    }

    void saveProject(Project project) {
        projectRepository.save(project);
    }

    boolean checkProjectName(String name) {
        Project project = new Project();
        project.setName(name);
        Example<Project> example = Example.of(project);
        Optional<Project> one = projectRepository.findOne(example);
        return !one.isPresent();
    }

    boolean deleteProject(Integer id) {
        projectRepository.deleteById(id);
        return true;
    }

    Project getProject(Integer id) {
        return projectRepository.getOne(id);
    }
}
